<template>
  <view class="page_root" data-page-name="例会管理" data-page-identification="j_qwv0agssga">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_aptztwv1qy 自定义模板_najys722ys -->
    <!-- 删除 -->
    <u-modal
      v-model="deleteVisible"
      title="删除"
      @confirm="deleteRecord"
      @cancel="cancelDeleteVisible"
      show-cancel-button="true"
    >
      确定删除该数据？
    </u-modal>
    <!-- 删除 -->
    <u-navbar
      title="例会记录"
      title-color="#fff"
      back-icon-color="#fff"
      :is-fixed="true"
      :border-bottom="false"
      title-width="250"
    >
      <template #right>
        <view class="right-icon" @click="showAdd"></view>
      </template>
    </u-navbar>
    <!-- 新建/编辑日例会 -->
    <!-- 表单弹窗 -->
    <u-popup v-model="state.addVisible" mode="center" width="100%" height="100%">
      <view class="add-or-edit-wrapper">
        <u-navbar
          back-icon-color="#fff"
          :title="state.modalTitle"
          title-color="#fff"
          :custom-back="navbarBackFn"
          title-width="400"
          :border-bottom="false"
        >
        </u-navbar>
        <scroll-view class="form-body" scroll-y>
          <view class="form-body-title">请填写以下例会信息</view>
          <view class="base-date-img">
            <view class="add-bot"></view>
          </view>
          <u-form :model="state.addForm" ref="addRef" :rules="addRule" label-position="top">
            <view class="base-form-data mgb16">
              <view class="form-title">基本信息</view>
              <!-- 区域 -->
              <u-form-item label="区域" prop="areaCode" required>
                <u-input
                  border
                  v-model="state.addForm.areaName"
                  placeholder="请选择区域"
                  readonly
                  clickable
                  type="select"
                  suffix-icon="arrowdown"
                  @click="showPicker('areaCode')"
                />
                <van-popup v-model:show="show.areaCode" position="bottom">
                  <van-picker
                    :columns="state.areaNameList"
                    show-toolbar
                    :columns-field-names="{ text: 'label', value: 'value' }"
                    @confirm="onConfirm('areaCode', $event)"
                    @cancel="() => (show.areaCode = false)"
                  />
                </van-popup>
              </u-form-item>
              <!-- 工厂 -->
              <template v-if="currentTab === '周例会（区域风险）' || currentTab === '日例会'">
                <u-form-item label="工厂">
                  <u-input
                    border
                    v-model="state.addForm.factoryNameList"
                    placeholder="请选择工厂（多选）"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('factoryCodeList')"
                  />
                  <van-popup
                    v-model:show="show.factoryCodeList"
                    position="bottom"
                    :close-on-click-overlay="false"
                  >
                    <view class="fixed-check-box-content">
                      <view class="check-group-button">
                        <view class="cancel-btn" @click="show.factoryCodeList = false">取消</view>
                        <view class="ok-btn" @click="show.factoryCodeList = false">确认</view>
                      </view>
                      <scroll-view scroll-y class="check-scroll">
                        <van-checkbox-group
                          v-model="state.addForm.factoryCodeList"
                          direction="horizontal"
                          @change="handleFactoryCodeListChange"
                        >
                          <van-cell-group inset>
                            <van-cell v-for="f in state.factoryList" :key="f.value">
                              <template #right-icon>
                                <van-checkbox :name="f.value">{{ f.label }}</van-checkbox>
                              </template>
                            </van-cell>
                          </van-cell-group>
                        </van-checkbox-group>
                      </scroll-view>
                    </view>
                  </van-popup>
                </u-form-item>
              </template>
              <template v-else>
                <u-form-item label="工厂" prop="factoryCode" required="true">
                  <u-input
                    border
                    v-model="state.addForm.factoryName"
                    placeholder="请选择工厂"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('factoryCode')"
                  />
                  <van-popup v-model:show="show.factoryCode" position="bottom">
                    <van-picker
                      :columns="state.factoryList"
                      show-toolbar
                      :columns-field-names="{ text: 'label', value: 'value' }"
                      @confirm="onConfirm('factoryCode', $event)"
                      @cancel="() => (show.factoryCode = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>

              <!-- 产品线 -->
              <template v-if="currentTab === '周例会（区域风险）' || currentTab === '日例会'">
                <u-form-item label="产品线">
                  <u-input
                    border
                    v-model="state.addForm.productLineNameList"
                    placeholder="请选择产品线（多选）"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('productLineList')"
                  />
                  <van-popup
                    v-model:show="show.productLineList"
                    position="bottom"
                    :close-on-click-overlay="false"
                  >
                    <view class="fixed-check-box-content">
                      <view class="check-group-button">
                        <view class="cancel-btn" @click="show.productLineList = false">取消</view>
                        <view class="ok-btn" @click="show.productLineList = false">确认</view>
                      </view>
                      <scroll-view scroll-y class="check-scroll">
                        <van-checkbox-group
                          v-model="state.addForm.productLineList"
                          direction="horizontal"
                          @change="handleproductLineListChange"
                        >
                          <van-cell-group inset>
                            <van-cell v-for="f in state.allProductLineList" :key="f.value">
                              <template #right-icon>
                                <van-checkbox :name="f.value">{{ f.label }}</van-checkbox>
                              </template>
                            </van-cell>
                          </van-cell-group>
                        </van-checkbox-group>
                      </scroll-view>
                    </view>
                  </van-popup>
                </u-form-item>
              </template>
              <template v-else>
                <u-form-item label="产品线" required prop="productLine">
                  <u-input
                    border
                    v-model="state.addForm.productLineName"
                    placeholder="请选择产品线"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('productLine')"
                  />
                  <van-popup v-model:show="show.productLine" position="bottom">
                    <van-picker
                      :columns="state.productLineList"
                      show-toolbar
                      :columns-field-names="{ text: 'label', value: 'value' }"
                      @confirm="onConfirm('productLine', $event)"
                      @cancel="() => (show.productLine = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>

              <!-- 项目阶段 -->
              <template v-if="currentTab === '日例会' || currentTab === '周例会（未验收风险）'">
                <u-form-item label="项目阶段">
                  <u-input
                    border
                    v-model="state.addForm.projectPhase"
                    placeholder="请选择阶段（产品线多选则禁用）"
                    readonly
                    clickable
                    type="select"
                    :disabled="state.addForm.productLineList.length > 1"
                    @click="showPicker('projectPhase')"
                  />
                  <van-popup v-model:show="show.projectPhase" position="bottom">
                    <van-picker
                      :columns="state.milepostList"
                      show-toolbar
                      :columns-field-names="{ text: 'label', value: 'value' }"
                      @confirm="onConfirm('projectPhase', $event)"
                      @cancel="() => (show.projectPhase = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>

              <!-- 项目状态 -->
              <template
                v-if="
                  currentTab === '周例会（已验收风险）' || currentTab === '周例会（未验收风险）'
                "
              >
                <u-form-item label="项目状态" required prop="projectStatus">
                  <u-input
                    border
                    v-model="state.addForm.projectStatus"
                    placeholder="请选择"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('projectStatus')"
                  />
                  <van-popup v-model:show="show.projectStatus" position="bottom">
                    <van-picker
                      :columns="state.statusList"
                      show-toolbar
                      :columns-field-names="{ text: 'label', value: 'value' }"
                      @confirm="onConfirm('projectStatus', $event)"
                      @cancel="() => (show.projectStatus = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>

              <template v-if="currentTab !== '日例会'">
                <u-form-item label="汇报时间区间">
                  <u-input
                    border
                    v-model="state.addForm.reportRangeName"
                    placeholder="请选择汇报时间区间"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('reportRangeList')"
                  />
                  <van-popup
                    v-model:show="show.reportRangeList"
                    position="bottom"
                    :style="{ height: '60vh' }"
                    :close-on-click-overlay="false"
                  >
                    <view class="fixed-check-box-content">
                      <scroll-view scroll-y class="check-scroll">
                        <van-picker-group
                          title="汇报时间区间"
                          :tabs="['开始日期', '结束日期']"
                          @confirm="onConfirm('reportRangeList', $event)"
                          @cancel="show.reportRangeList = false"
                        >
                          <van-date-picker v-model="state.addForm.reportStartTime" />
                          <van-date-picker
                            v-model="state.addForm.reportEndTime"
                            :min-date="formMinEndDate"
                          />
                        </van-picker-group>
                      </scroll-view>
                    </view>
                  </van-popup>
                </u-form-item>
              </template>

              <!-- 风险状态（currentTab !== '日例会'） -->
              <template v-if="currentTab !== '日例会'">
                <u-form-item label="风险状态" required prop="riskStatus">
                  <u-input
                    border
                    v-model="state.addForm.riskStatusName"
                    placeholder="请选择风险状态"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('riskStatus')"
                  />
                  <van-popup v-model:show="show.riskStatus" position="bottom">
                    <van-picker
                      :columns="state.fxztList"
                      :columns-field-names="{ text: 'label', value: 'value' }"
                      show-toolbar
                      @confirm="onConfirm('riskStatus', $event)"
                      @cancel="() => (show.riskStatus = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>

              <!-- 预计验收时间（仅未验收风险） -->
              <template v-if="currentTab === '周例会（未验收风险）'">
                <u-form-item label="预计验收时间" required prop="expectAcceptanceTime">
                  <u-input
                    border
                    v-model="state.addForm.expectAcceptanceTime"
                    placeholder="请选择预计验收时间"
                    readonly
                    clickable
                    type="select"
                    suffix-icon="arrowdown"
                    @click="showPicker('expectAcceptanceTime')"
                  />
                  <van-popup v-model:show="show.expectAcceptanceTime" position="bottom">
                    <van-date-picker
                      v-model="defaultDate"
                      type="date"
                      @confirm="(val) => onConfirm('expectAcceptanceTime', val)"
                      @cancel="() => (show.expectAcceptanceTime = false)"
                    />
                  </van-popup>
                </u-form-item>
              </template>
            </view>
            <view class="detail-content mgb16">
              <view class="form-title">详细内容</view>
              <!-- 文本区：根据 tab 判断 -->
              <template v-if="currentTab === '日例会'">
                <u-form-item label="拜访/协同状态" required prop="visitSituation">
                  <u-input
                    border
                    v-model="state.addForm.visitSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="项目阶段事件" required prop="projectPhaseEvents">
                  <u-input
                    border
                    v-model="state.addForm.projectPhaseEvents"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="跟踪情况" required prop="trackingSituation">
                  <u-input
                    border
                    v-model="state.addForm.trackingSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
              </template>

              <template v-if="currentTab === '周例会（区域风险）'">
                <u-form-item label="客情风险" required prop="projectPhaseEvents">
                  <u-input
                    border
                    v-model="state.addForm.projectPhaseEvents"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="协同状态" required>
                  <u-input
                    border
                    v-model="state.addForm.trackingSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
              </template>

              <template v-if="currentTab === '周例会（未验收风险）'">
                <u-form-item label="项目风险" required prop="visitSituation">
                  <u-input
                    border
                    v-model="state.addForm.visitSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="客情风险" required prop="projectPhaseEvents">
                  <u-input
                    border
                    v-model="state.addForm.projectPhaseEvents"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="协同状态" required>
                  <u-input
                    border
                    v-model="state.addForm.trackingSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
              </template>

              <template v-if="currentTab === '周例会（已验收风险）'">
                <u-form-item label="项目风险" required prop="visitSituation">
                  <u-input
                    border
                    v-model="state.addForm.visitSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="客情风险" required prop="projectPhaseEvents">
                  <u-input
                    border
                    v-model="state.addForm.projectPhaseEvents"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
                <u-form-item label="协同状态" required>
                  <u-input
                    border
                    v-model="state.addForm.trackingSituation"
                    type="textarea"
                    rows="3"
                    clickable
                  />
                </u-form-item>
              </template>
            </view>
            <view class="owner-msg">
              <view class="form-title">负责人信息</view>
              <!-- 汇报日期 -->
              <u-form-item label="汇报日期" required prop="reportTime">
                <u-input
                  border
                  v-model="state.addForm.reportTime"
                  placeholder="请选择日期"
                  readonly
                  clickable
                  type="select"
                  suffix-icon="arrowdown"
                  @click="show.reportTime = true"
                />
                <van-popup v-model:show="show.reportTime" position="bottom">
                  <van-date-picker
                    v-model="defaultDate"
                    @confirm="onConfirm('reportTime', $event)"
                    @cancel="() => (show.reportTime = false)"
                  />
                </van-popup>
              </u-form-item>
              <!-- 客成经理 -->
              <u-form-item label="客成经理" required prop="customerManager">
                <u-input
                  border
                  v-model="state.addForm.customerManager"
                  placeholder="请选择"
                  readonly
                  clickable
                  type="select"
                  suffix-icon="arrowdown"
                  @click="show.customerManager = true"
                />
                <van-popup v-model:show="show.customerManager" position="bottom">
                  <van-picker
                    :columns-field-names="{ text: 'label', value: 'value' }"
                    :columns="state.allUser"
                    @confirm="onConfirm('customerManager', $event)"
                    @cancel="() => (show.customerManager = false)"
                  />
                </van-popup>
              </u-form-item>
            </view>
          </u-form>
        </scroll-view>
        <!-- 底部操作栏 -->
        <view class="footer-bar">
          <van-button type="default" @click="cancelMeet" icon="cross">取消</van-button>
          <van-button
            type="primary"
            :loading="state.submitLoading"
            @click="confirmAdd"
            icon="completed"
          >
            {{ state.fatherLoading ? '保存中...' : '保存' }}
          </van-button>
        </view>
      </view>
    </u-popup>

    <!-- 新建/编辑日例会 -->
    <!-- 筛选 -->
    <u-mask :show="state.loading">
      <view class="warp">
        <view class="rect" @tap.stop>加载中....</view>
      </view>
    </u-mask>
    <van-tabs
      @change="tabChange"
      shrink
      v-model:active="currentTab"
      background="transparent"
      color="#ffffff"
      :ellipsis="false"
      title-inactive-color="#ffffff"
      title-active-color="#ffffff"
    >
      <van-tab v-for="(tab, index) in tabs" :title="tab" :name="tab"></van-tab>
    </van-tabs>
    <van-config-provider :theme-vars="themeVars">
      <view class="filters-row">
        <!-- 左侧两项：作为一组靠左显示 -->
        <view class="left-group">
          <view class="dropdown-card">
            <van-dropdown-menu>
              <van-dropdown-item
                v-model="state.searchForm.areaCode"
                :title="getAreaNameTitle"
                :options="areaNameOptions"
                @change="handleFilterChange"
              />
            </van-dropdown-menu>
          </view>

          <view class="dropdown-card">
            <van-dropdown-menu>
              <van-dropdown-item
                v-model="state.searchForm.productLine"
                :title="getProductLineTitle"
                :options="productLineOptions"
                @change="handleFilterChange"
              />
            </van-dropdown-menu>
          </view>
          <view class="dropdown-card">
            <van-dropdown-menu>
              <van-dropdown-item
                v-model="state.searchForm.customerManager"
                :title="getCustomTitle"
                :options="customerManagerOptions"
                @change="handleFilterChange"
              />
            </van-dropdown-menu>
          </view>
          <view class="dropdown-card">
            <van-dropdown-menu>
              <van-dropdown-item
                v-model="state.searchForm.reportTimeList"
                title="汇报日期"
                ref="searchTimeRef"
              >
                <van-picker-group
                  :tabs="['起始日期', '结束日期']"
                  @confirm="onConfirmSearchTime($event)"
                  @cancel="cancelSearchTime"
                >
                  <van-date-picker v-model="state.searchForm.startTime" />
                  <van-date-picker
                    v-model="state.searchForm.endTime"
                    :min-date="searchMinEndDate"
                  />
                </van-picker-group>
              </van-dropdown-item>
            </van-dropdown-menu>
          </view>
        </view>
      </view>
    </van-config-provider>
    <view class="container">
      <!-- 顶部筛选区域，固定定位 -->
      <scroll-view scroll-y class="main" @scrolltolower="handleScrollToLower">
        <view class="meet-item" v-for="(item, index) in state.dataSource" :key="item.id">
          <view class="meet-top">
            <view class="meet-top-left">
              <view class="area-name">{{ item.areaName }}</view>
              <view class="productline-name">{{ item.productLineName }}</view>
            </view>
            <view class="meet-top-right" v-if="item.projectStatus">{{ item.projectStatus }}</view>
          </view>
          <view class="factory-name mgb16">{{ item.factoryName }}</view>
          <template v-if="currentTab !== '周例会（区域风险）'">
            <view class="content-label mgb8">
              <span v-if="currentTab === '日例会'">拜访情况或协同情况：</span>
              <span v-else>项目风险：</span>
            </view>
            <view class="content-value mgb16">{{ item.visitSituation }}</view>
          </template>
          <view class="content-label mgb8">
            <span v-if="currentTab === '周例会（区域风险）'">客情风险：</span>
            <span v-else>项目阶段事件：</span>
          </view>
          <view class="content-value mgb16">{{ item.projectPhaseEvents }}</view>
          <view class="content-label mgb8">
            <span v-if="currentTab === '日例会'">跟踪情况：</span>
            <span v-else>协同状态：</span>
          </view>
          <view class="content-value mgb16">{{ item.trackingSituation }}</view>
          <view class="meet-bottom">
            <view class="bottom-left">
              <span class="bottom-label">客成经理:</span>
              <span class="bottom-value">{{ item.customerManager }}</span>
            </view>
            <view class="bottom-right">
              <span class="bottom-label">汇报日期：</span>
              <span class="bottom-value">{{ item.reportTime }}</span>
            </view>
          </view>
          <u-line color="#D9D9D9" class="third-line" margin="24rpx 0" />
          <view class="opeartion-btn">
            <van-config-provider :theme-vars="themeVars">
              <van-button @click="handleEdit(item)" style="width: 150rpx">编辑</van-button>
            </van-config-provider>
            <van-config-provider :theme-vars="themeVars">
              <van-button style="width: 150rpx" type="primary" @click="showDeleteMoadal(item.id)"
                >删除</van-button
              >
            </van-config-provider>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- end vid_aptztwv1qy 自定义模板_najys722ys -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/
  import { onReachBottom } from '@dcloudio/uni-app';
  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001243';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_aptztwv1qy_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_najys722ys ref 的引用
  const vid_aptztwv1qy_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_aptztwv1qy_ref };

  const showState = reactive({
    vid_aptztwv1qy_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_mh7647hrw4 = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  import { showSuccessToast, showFailToast } from 'vant';
  // 按需导入 Vant 3 组件
  import {
    Form,
    Field,
    CellGroup,
    Cell,
    Picker,
    Popup,
    Uploader,
    Button,
    DatePicker,
    Toast,
    Col,
    Row,
    Icon,
    Tab,
    Tabs,
    Checkbox,
    CheckboxGroup,
    PickerGroup,
    DropdownMenu,
    DropdownItem,
    ConfigProvider,
  } from 'vant';
  import 'vant/lib/index.css';
  import { nextTick } from 'vue';

  // 页面内注册 Vant 组件
  const { appContext } = getCurrentInstance();
  [
    ['van-form', Form],
    ['van-field', Field],
    ['van-cell-group', CellGroup],
    ['van-cell', Cell],
    ['van-picker', Picker],
    ['van-popup', Popup],
    ['van-uploader', Uploader],
    ['van-button', Button],
    ['van-date-picker', DatePicker],
    ['van-col', Col],
    ['van-row', Row],
    ['van-icon', Icon],
    ['van-tab', Tab],
    ['van-tabs', Tabs],
    ['van-checkbox-group', CheckboxGroup],
    ['van-checkbox', Checkbox],
    ['van-picker-group', PickerGroup],
    ['van-dropdown-menu', DropdownMenu],
    ['van-dropdown-item', DropdownItem],
    ['van-config-provider', ConfigProvider],
  ].forEach(([name, comp]) => appContext.app.component(name, comp));
  const themeVars = reactive({
    'button-default-background': 'rgba(255,255,255,0.80)',
    'button-primary-background': 'rgba(255,255,255,0.80)',
    'button-primary-border-color': 'none',
    'button-primary-color': '#000000',
    'button-default-border-color': 'none',
    'button-default-color': 'rgba(0,0,0,0.65)',
  });
  const currentTab = ref('日例会');
  const tabs = ['日例会', '周例会（区域风险）', '周例会（未验收风险）', '周例会（已验收风险）'];
  onMounted(() => {
    setPageStyle('lihui-page');
    getAreaList();
    getAllUser();
    getAllProductLineList();
    getData(true);
    getUserInfo();
  });

  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      if (appDiv) {
        appDiv.className = '';

        // 再添加当前需要的类
        if (newClass) {
          appDiv.classList.add(newClass);
        }
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  // 显示哪个 picker
  const show = reactive({
    areaCode: false,
    factoryCode: false,
    factoryName: false,
    factoryCodeList: false,
    reportRangeList: false,
    productLineList: false,
    productLine: false,
    projectPhase: false,
    reportTime: false,
    customerManager: false,
    expectAcceptanceTime: false,
    riskStatus: false,
  });
  // 打开 picker
  function showPicker(type) {
    nextTick(() => {
      show[type] = true;
    });
    switch (type) {
      case 'areaCode':
        getAreaList();
        break;
      case 'factoryCodeList':
        getProjectByArea();
        break;
      case 'productLineList':
        getAllProductLineList();
        break;
      case 'projectPhase':
        getMilepostList();
        break;
      case 'factoryCode':
        getProjectByArea();
        break;
      case 'productLine':
        getProductLineByFactory();
        break;
      case 'projectStatus':
        getStatusList();
        break;
    }
  }

  // picker 确认事件（你原先逻辑的完全延续）
  function onConfirm(type, val) {
    const selected = val.selectedOptions?.[0];
    if (['factoryCode'].includes(type)) {
      if (selected) {
        state.addForm[`${type.replace('Code', '')}Name`] = selected.label;
        state.addForm[type] = selected.value;
      }
    } else if (type === 'areaCode') {
      if (selected) {
        state.addForm.areaName = selected.label;
        state.addForm.areaCode = selected.value;
      }
      console.log('到了');

      state.addForm.factoryCode = undefined;
      state.addForm.factoryName = undefined;
      state.addForm.productLine = undefined;
      state.addForm.productLineName = undefined;
      state.addForm.productLineList = [];
      state.addForm.productLineNameList = [];
      state.addForm.factoryCodeList = [];
      state.addForm.factoryNameList = [];
    } else if (type === 'reportTime') {
      const year = val.selectedValues[0];
      const month = val.selectedValues[1];
      const day = val.selectedValues[2];
      state.addForm.reportTime = `${year}-${month}-${day}`;
    } else if (type === 'expectAcceptanceTime') {
      const year = val.selectedValues[0];
      const month = val.selectedValues[1];
      const day = val.selectedValues[2];
      state.addForm.expectAcceptanceTime = `${year}-${month}-${day}`;
    } else if (type === 'reportRangeList') {
      console.log(val[0].selectedValues);

      const startYear = val[0].selectedValues[0];
      const startMonth = val[0].selectedValues[1];
      const startDay = val[0].selectedValues[2];
      const endYear = val[1].selectedValues[0];
      const endMonth = val[1].selectedValues[1];
      const endDay = val[1].selectedValues[2];
      state.addForm.reportRangeName = `${startYear}-${startMonth}-${startDay}-${endYear}-${endMonth}-${endDay}`;
      state.addForm.reportRangeList = [
        val[0].selectedValues.join('-'),
        val[1].selectedValues.join('-'),
      ];
    } else if (type === 'factoyCode') {
      state.addForm.productLine = undefined;
      state.addForm.productLineName = undefined;
      state.addForm.projectPhase = undefined;
    } else if (type === 'productLine') {
      if (selected) {
        state.addForm.productLineName = selected.label;
        state.addForm.productLine = selected.value;
      }
    } else if (type === 'riskStatus') {
      if (selected) {
        state.addForm.riskStatusName = selected.label;
        state.addForm.riskStatus = selected.value;
      }
    } else {
      console.log(type, 'type');
      state.addForm[type] = val.selectedValues[0];
    }

    // 关闭 picker
    show[type] = false;

    // 联动逻辑
    switch (type) {
      case 'areaCode':
        state.addForm.factoryCode = undefined;
        state.addForm.productLine = undefined;
        state.addForm.productLineList = [];
        state.addForm.factoryCodeList = [];
        break;
      case 'factoryCode':
        state.addForm.productLine = undefined;
        state.addForm.projectPhase = undefined;
        break;
      case 'productLineList':
        state.addForm.projectPhase = undefined;
        break;
      case 'environment':
        environmentChange();
        break;
      case 'production':
        productChange();
        break;
    }
  }
  const headerOffset = ref(260);
  const topHeightNum = ref();
  const calcTableHeight = () => {
    let topHeight = document.querySelector('.top-classification');
    state.tableHeight = window.innerHeight - 170 - headerOffset.value;
  };

  onMounted(() => {
    calcTableHeight();
    window.addEventListener('resize', calcTableHeight);
  });
  onBeforeUnmount(() => {
    window.removeEventListener('resize', calcTableHeight);
  });
  const defaultDate = [
    String(new Date().getFullYear()),
    String(new Date().getMonth() + 1).padStart(2, '0'),
    String(new Date().getDate()).padStart(2, '0'),
  ];
  const selectHolder = '请选择';
  const inputHolder = '请输入';
  const userInfoStorage = localStorage.getItem('al__USER_INFO');
  const taskLeader = JSON.parse(userInfoStorage);

  const state = reactive({
    loading: false,
    hasMore: true,
    searchForm: {
      reportTimeList: [],
      reportTimeName: undefined,
      startTime: defaultDate,
      endTime: defaultDate,
      areaCode: undefined,
      customerManager: undefined,
      productLine: undefined,
    },
    dataSource: [],
    areaNameList: [],
    searchAreaNameList: [],
    projectList: [],
    allUser: [],
    searchAllUser: [],
    analysisVisible: false,
    addForm: {
      areaCode: undefined,
      areaName: undefined,
      factoryCode: undefined,
      productLine: undefined,
      onlineUsageRate: undefined,
      riskStatus: undefined,
      riskStatusName: undefined,
      projectStatus: undefined,
      projectPhase: undefined,
      reportTime: dayjs().format('YYYY-MM-DD'),
      customerManager: undefined,
      visitSituation: undefined,
      projectPhaseEvents: undefined,
      productLineList: [],
      productLineNameList: undefined,
      factoryCodeList: [],
      factoryNameList: undefined,
      trackingSituation: undefined,
      reportRangeList: [],
      reportStartTime: defaultDate,
      reportEndTime: defaultDate,
      reportRangeName: undefined,
    },
    addVisible: false,
    modalTitle: '',
    productLineList: [],
    allProductLineList: [],
    allSearchProductLineList: [],
    fxztList: [
      {
        label: '未构成风险',
        value: 'NO_RISK',
      },
      {
        label: '低风险',
        value: 'LOW_RISK',
      },
      {
        label: '中风险',
        value: 'MEDIUM_RISK',
      },
      {
        label: '高风险',
        value: 'HIGH_RISK',
      },
    ],
    factoryList: [],
    submitLoading: false,
    statusList: [],
    milepostList: [],
    tableHeight: 520,
    exportVisible: false,
    exportLoading: false,
    exportType: undefined,
    exportDateList: [],
    userInfo: {},
  });
  function getUserInfo() {
    get('/base/api/v1/user/userinfo').then((data) => {
      if (data.status !== 'success') {
        state.userInfo = {};
        return;
      }
      state.userInfo = data.data.userItem;
      console.log(data.data.uFormItem, 'asdsa');
      console.log(state.addForm.customerManager, 'state.addForm.customerManager前');

      state.addForm.customerManager = data.data.userItem.name;
      console.log(state.addForm.customerManager, 'state.addForm.后');
    });
  }
  // 计算属性：结束日期最小可选为开始日期
  const searchMinEndDate = computed(() => {
    const start = state.searchForm.startTime;
    if (!start || start.length !== 3) {
      return new Date(2000, 0, 1);
    } // 🧩 防止解构空值
    const [y, m, d] = start;
    return new Date(`${y}-${m}-${d}`);
  });

  const formMinEndDate = computed(() => {
    const start = state.addForm.reportStartTime;
    if (!start || start.length !== 3) {
      // 🧩 没选开始日期时，返回一个合理的最小日期
      return new Date(2000, 0, 1);
    }
    const [y, m, d] = start;
    return new Date(`${y}-${m}-${d}`);
  });

  /**
   * 监听开始时间变化：如果结束时间早于开始时间，自动修正
   */
  watch(
    () => state.searchForm.startTime,
    (newStart) => {
      if (!newStart) return;
      const [sy, sm, sd] = newStart;
      const start = new Date(`${sy}-${sm}-${sd}`);
      const [ey, em, ed] = state.searchForm.endTime;
      const end = new Date(`${ey}-${em}-${ed}`);
      if (end < start) {
        // 👇 如果结束时间比开始时间早，自动同步
        state.searchForm.endTime = [...newStart];
      }
    },
    { deep: true },
  );
  // 监听表单时间区间
  watch(
    () => state.addForm.reportStartTime,
    (newStart) => {
      if (!newStart || newStart.length !== 3) return; // 🧩 防止空值报错

      const [sy, sm, sd] = newStart;
      const start = new Date(`${sy}-${sm}-${sd}`);

      const endTime = state.addForm.reportEndTime;

      // 🧩 如果还没选结束时间，直接同步为开始时间
      if (!endTime || endTime.length !== 3) {
        state.addForm.reportEndTime = [...newStart];
        return;
      }

      const [ey, em, ed] = endTime;
      const end = new Date(`${ey}-${em}-${ed}`);

      // 🧩 结束时间早于开始时间时自动修正
      if (end < start) {
        state.addForm.reportEndTime = [...newStart];
      }
    },
    { deep: true },
  );

  // 多选工厂改变时格式化内容复制给展示组件
  function handleFactoryCodeListChange() {
    // ✅ 计算对应 label 数组
    const selectedLabels = state.factoryList
      .filter((item) => state.addForm.factoryCodeList.includes(item.value))
      .map((item) => item.label);

    // ✅ 转成字符串
    const selectedLabelString = selectedLabels.join('、');

    console.log(selectedLabels);
    // ['【南方】宜城南方', '【南方】常山南方', '【南方】三明南方', '【南方】宜兴天山', '【南方】安徽广德洪山']

    console.log(selectedLabelString);
    state.addForm.factoryNameList = selectedLabelString;
    // 【南方】宜城南方、【南方】常山南方、【南方】三明南方、【南方】宜兴天山、【南方】安徽广德洪山
    // show.factoryCodeList = false;
  }

  // 多选产品线改变时格式化内容复制给展示组件
  function handleproductLineListChange() {
    // ✅ 计算对应 label 数组
    const selectedLabels = state.allProductLineList
      .filter((item) => state.addForm.productLineList.includes(item.value))
      .map((item) => item.label);

    // ✅ 转成字符串
    const selectedLabelString = selectedLabels.join('、');
    state.addForm.productLineNameList = selectedLabelString;
    // 【南方】宜城南方、【南方】常山南方、【南方】三明南方、【南方】宜兴天山、【南方】安徽广德洪山
    // show.productLineList = false;
  }
  function getProductLineByFactory() {
    if (!state.addForm.factoryCode) {
      state.productLineList = [];
      return;
    }
    get(`/solution-crm/api/v1/base_data/product_line/${state.addForm.factoryCode}`).then((data) => {
      state.productLineList = data.data.map((item) => {
        return {
          label: item.productLineName,
          value: item.productLine,
        };
      });
    });
  }
  function getAllProductLineList() {
    get('/solution-ppm-basic-data/api/v1/product_line/all').then((data) => {
      state.allProductLineList = data.data.map((item) => {
        return {
          label: item.productLineName,
          value: item.productLineCode,
        };
      });
      state.allSearchProductLineList = [{ label: '全部', value: '' }, ...state.allProductLineList];
    });
  }
  // 根据区域查工厂
  function getProjectByArea() {
    if (!state.addForm.areaCode) {
      state.factoryList = [];
      return;
    }
    get(`/solution-crm/api/v1/base_data/factory/${state.addForm.areaCode}`).then((data) => {
      state.factoryList = data.data.map((item) => {
        return {
          label: item.factoryShortName,
          value: item.factoryCode,
        };
      });
    });
  }
  function getMilepostList() {
    state.milepostList = [];
    if (!state.addForm.productLine && state.addForm.productLineList.length == 0) {
      return;
    }
    get(
      `/solution-crm/api/v1/base_data/stage/${
        state.addForm.productLine || state.addForm.productLineList[0]
      }`,
    ).then((data) => {
      state.milepostList = data.data.map((item) => {
        return {
          label: item.stageName,
          value: item.stageName,
        };
      });
    }); // 问题类型
  }
  function getStatusList() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/PROJECT_STATUS').then((data) => {
      state.statusList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }

  const addRule = {
    areaCode: [{ required: true, message: '请选择区域', trigger: 'blur' }],
    factoryCode: [{ required: true, message: '请选择工厂', trigger: 'blur' }],
    productLine: [{ required: true, message: '请选择产品线', trigger: 'blur' }],
    riskStatus: [{ required: true, message: '请选择风险状态', trigger: 'blur' }],
    projectPhase: [
      {
        required: false,
        message: '请选择项目阶段',
        trigger: 'blur',
      },
    ],
    reportTime: [{ required: true, message: '请选择汇报时间', trigger: 'blur' }],
    expectAcceptanceTime: [{ required: false, message: '请选择预计验收时间', trigger: 'blur' }],
    customerManager: [{ required: true, message: '请选择客成经理', trigger: 'blur' }],
    projectStatus: [{ required: true, message: '请选择项目状态', trigger: 'blur' }],
    visitSituation: [{ required: true, message: '请输入', trigger: 'blur' }],
    projectPhaseEvents: [{ required: true, message: '请输入', trigger: 'blur' }],
    trackingSituation: [{ required: true, message: '请输入', trigger: 'blur' }],
  };
  const tabChange = () => {
    pagination.value.current = 1;
    pagination.value.pageSize = 10;
    state.hasMore = true;
    state.dataSource = []; // 👈 防止 tab 切换后残留旧数据
    getData(true);
  };
  const tabMap = {
    日例会: 'DAILY_MEETING',
    '周例会（区域风险）': 'WEEKLY_MEETING',
    '周例会（未验收风险）': 'UNACCEPTED_WEEKLY_MEETING',
    '周例会（已验收风险）': 'ACCEPTED_WEEKLY_MEETING',
  };
  const productLineOptions = computed(() => {
    return state.allSearchProductLineList.map((item) => ({
      text: item.label,
      value: item.value,
    }));
  });
  const areaNameOptions = computed(() => {
    return state.searchAreaNameList.map((item) => ({
      text: item.label,
      value: item.value,
    }));
  });
  const customerManagerOptions = computed(() => {
    return state.searchAllUser.map((item) => ({
      text: item.label,
      value: item.value,
    }));
  });
  const getProductLineTitle = computed(() => {
    const value = state.searchForm.productLine;
    const option = productLineOptions.value.find((item) => item.value === value);
    return option ? option.text : '产品线'; // 默认标题
  });
  const getAreaNameTitle = computed(() => {
    const value = state.searchForm.areaCode;
    const option = areaNameOptions.value.find((item) => item.value === value);
    return option ? option.text : '区域'; // 默认标题
  });
  const getCustomTitle = computed(() => {
    const value = state.searchForm.customerManager;
    const option = customerManagerOptions.value.find((item) => item.value === value);
    return option ? option.text : '客成经理'; // 默认标题
  });
  const searchTimeRef = ref(null);
  function onConfirmSearchTime(val) {
    console.log(val);
    const startYear = val[0].selectedValues[0];
    const startMonth = val[0].selectedValues[1];
    const startDay = val[0].selectedValues[2];
    const endYear = val[1].selectedValues[0];
    const endMonth = val[1].selectedValues[1];
    const endDay = val[1].selectedValues[2];
    state.searchForm.reportTimeList = `${startYear}-${startMonth}-${startDay}---${endYear}-${endMonth}-${endDay}`;
    state.searchForm.reportTimeList = [
      val[0].selectedValues.join('-'),
      val[1].selectedValues.join('-'),
    ];
    searchTimeRef.value.toggle();

    handleFilterChange();
  }
  function cancelSearchTime() {
    searchTimeRef.value.toggle();
  }
  const dataLoading = ref(false);
  async function handleFilterChange() {
    // 用户点了筛选后
    state.hasMore = true;
    state.loading = false;
    pagination.value.current = 1;
    getData(true);
  }

  async function getData(isRefresh = false) {
    if (state.loading || !state.hasMore) return;

    state.loading = true;
    if (isRefresh) {
      pagination.value.current = 1;
      state.dataSource = [];
      state.hasMore = true;
    }

    try {
      const res = await post('/solution-crm/api/v1/meeting_minutes/search', {
        pageNumber: pagination.value.current,
        pageSize: pagination.value.pageSize,
        meetingType: tabMap[currentTab.value],
        customerManager: state.searchForm.customerManager,
        reportTimeList: state.searchForm.reportTimeList,
        areaCode: state.searchForm.areaCode,
        productLine: state.searchForm.productLine,
      });

      if (res.code !== 200) {
        showFailToast(res.message);
        state.dataSource = [];
        pagination.value.total = 0;
        state.hasMore = false;
        return;
      }

      const list = res.data?.content || [];
      const total = res.data?.totalElements || 0;

      // 拼接数据
      if (isRefresh) {
        state.dataSource = list;
      } else {
        state.dataSource = [...state.dataSource, ...list];
      }

      pagination.value.total = total;

      // 判断是否还有更多
      if (state.dataSource.length >= total || list.length === 0) {
        state.hasMore = false;
      } else {
        pagination.value.current++;
      }
    } catch (err) {
      console.error(err);
      showFailToast('加载失败');
    } finally {
      state.loading = false;
    }
  }
  function handleScrollToLower() {
    if (!state.loading) {
      getData(false); // 加载下一页
    }
  }
  function resetData() {
    pagination.value.current = 1;
    pagination.value.pageSize = 10;
    state.searchForm.areaCode =
      state.searchForm.customerManager =
      state.searchForm.productLine =
        undefined;
    state.searchForm.reportTimeList = [];
    state.searchForm.reportTimeName = undefined;
    getData();
  }
  // 区域
  function getAreaList() {
    get('/solution-crm/api/v1/base_data/area').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.areaNameList = data.data.map((item) => {
        return {
          label: item.areaName,
          value: item.areaCode,
        };
      });
      state.searchAreaNameList = [{ label: '全部', value: '' }, ...state.areaNameList];
    });
  }
  function getAllUser() {
    get('/solution-crm/api/v1/base_data/customer_success_team_member').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.allUser = data.data.map((item) => {
        return {
          label: item.name,
          value: item.name,
        };
      });
      state.searchAllUser = [{ label: '全部', value: '' }, ...state.allUser];
    });
  }
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
    showTotal: (total) =>
      `共 ${total} 个项目 第${pagination.value.current}/${Math.ceil(
        total / pagination.value.pageSize,
      )}页`,
  });

  function confirmMeet(record) {
    record.isEdit = false;
  }
  function showAdd() {
    state.modalTitle = `新建${currentTab.value}`;
    state.addForm.customerManager = state.userInfo.name;
    state.addForm.reportTime = dayjs().format('YYYY-MM-DD');
    currentData.value = {
      areaCode: undefined,
      factoryCode: undefined,
      productLine: undefined,
      onlineUsageRate: undefined,
      projectStatus: undefined,
      projectPhase: undefined,
      reportTime: dayjs().format('YYYY-MM-DD'),
      customerManager: state.userInfo.name,
      visitSituation: undefined,
      projectPhaseEvents: undefined,
      trackingSituation: undefined,
    };
    state.addVisible = true;
    nextTick(() => {
      addRef.value.setRules(addRule);
    });
  }
  function navbarBackFn() {
    cancelMeet();
  }
  function cancelMeet() {
    state.addVisible = false;
    currentData.value = {};
    state.addForm = {
      areaCode: undefined,
      areaName: undefined,
      factoryCode: undefined,
      productLine: undefined,
      onlineUsageRate: undefined,
      riskStatus: undefined,
      riskStatusName: undefined,
      projectStatus: undefined,
      projectPhase: undefined,
      reportTime: dayjs().format('YYYY-MM-DD'),
      customerManager: undefined,
      visitSituation: undefined,
      projectPhaseEvents: undefined,
      productLineList: [],
      productLineNameList: undefined,
      factoryCodeList: [],
      factoryNameList: undefined,
      trackingSituation: undefined,
      reportRangeList: [],
      reportStartTime: defaultDate,
      reportEndTime: defaultDate,
      reportRangeName: undefined,
    };
  }
  const addRef = ref(null);
  const currentData = ref({});
  function confirmAdd() {
    addRef.value
      .validate()
      .then(() => {
        console.log('校验通过');
        const api = currentData.value.id ? put : post;
        state.submitLoading = true;
        api('/solution-crm/api/v1/meeting_minutes', {
          ...state.addForm,
          meetingType: tabMap[currentTab.value],
        })
          .then((data) => {
            if (data.code !== 200) {
              showFailToast(data.message);
              return;
            }
            showSuccessToast(data.message);
            cancelMeet();
            getData(true);
          })
          .finally(() => {
            state.submitLoading = false;
          });
      })
      .catch((err) => {
        console.error('校验失败', err);
      })
      .finally(() => {});
  }
  function handleEdit(record) {
    state.modalTitle = `编辑${currentTab.value}`;
    get(`/solution-crm/api/v1/meeting_minutes/${record.id}`).then(async (data) => {
      Object.assign(state.addForm, data.data);
      state.addForm.reportRangeList = [data.data.reportRangeStart, data.data.reportRangeEnd];
      state.addForm.reportRangeName = `${data.data.reportRangeStart}-${data.data.reportRangeEnd}`;
      state.addForm.riskStatusName = data.data.riskStatusStr;
      state.addForm.productLineList = data.data.productLineList || [];
      state.addForm.factoryCodeList = data.data.factoryCodeList || [];
      state.addForm.factoryNameList = data.data.factoryName;
      state.addForm.productLineNameList = data.data.productLineName;
      await getAreaList();
      if (currentTab.value === '周例会（区域风险）') {
        await getAllProductLineList();
      }
      if (data.data.areaCode) {
        await getProjectByArea();
      }
      if (data.data.factoryCode) {
        await getProductLineByFactory();
      }
      if (
        (currentTab === '周例会（区域风险）' || currentTab === '日例会') &&
        data.data.factoryCodeList.length > 0
      ) {
        handleFactoryCodeListChange();
      }

      if (
        (currentTab === '周例会（区域风险）' || currentTab === '日例会') &&
        data.data.productLineList.length > 0
      ) {
        handleproductLineListChange();
      }

      state.addVisible = true;
      currentData.value = data.data;
    });
  }
  const deleteId = ref();
  const deleteVisible = ref();
  function showDeleteMoadal(id) {
    deleteId.value = id;
    deleteVisible.value = true;
  }
  function cancelDeleteVisible() {
    deleteId.value = undefined;
    deleteVisible.value = false;
  }
  function deleteRecord(id) {
    del(`/solution-crm/api/v1/meeting_minutes/${deleteId.value}`).then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      showSuccessToast(data.message);
      cancelDeleteVisible();
      getData(true);
    });
  }
  const colorMap = {
    未构成风险: '#52c41a', // 绿色
    低风险: '#fadb14', // 鲜亮的亮黄，和橙色区别大
    中风险: '#ffa940', // 橙色
    高风险: '#ff4d4f', // 红色
  };

  function getColor(text) {
    return colorMap[text] || '#52c41a';
  }
  //     导出
  function showExport() {
    state.exportType = currentTab.value;
    state.exportLoading = true;
    post(
      '/solution-crm/api/v1/meeting_minutes/export',
      { ...state.searchForm, meetingType: tabMap[currentTab.value] },
      {
        responseType: 'arraybuffer',
      },
    ).then((data) => {
      downloadExcel(data, `${state.exportType}.xlsx`);
      state.exportLoading = false;
    });
  }
  function downloadExcel(response, name) {
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob); // 创建下载的链接
    downloadElement.href = href;
    downloadElement.download = name; // 下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); // 点击下载
    document.body.removeChild(downloadElement); // 下载完成移除元素
    window.URL.revokeObjectURL(href);
    return href;
  }

  function cancelExport() {
    state.exportVisible = false;
    state.exportDateList = [];
    state.exportType = undefined;
  }
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: hidden;
    background-image: url('http://10.40.0.33:9001/file-storage/540302650699495424-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
  }
  .page-title {
    display: flex;
    justify-content: space-between;
    padding: 10rpx;
    color: #fff;
    font-weight: 600;
    align-items: center;
    padding: 10rpx 16rpx;
  }
  .container {
    position: relative;
    height: 100vh;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }

  // 左右布局
  .filters-row {
    display: flex;
    align-items: center;
    // padding: 56rpx 20rpx 18rpx 20rpx;
    padding: 20rpx;
    gap: 12rpx;
  }

  /* 左侧组：包含两个卡片，靠左显示（默认） */
  .left-group {
    display: flex;
    gap: 12rpx; /* 两个下拉之间的间隔 */
    align-items: center;
    /* 不设置宽度，按内容大小占位，右侧元素会被推到右 */
  }

  /* 右侧组：放“更多”并靠右 */
  .right-group {
    margin-left: auto; /* 把右侧推到容器最右 */
    display: flex;
    align-items: center;
  }

  /* 通用卡片样式（每个独立下拉） */
  .dropdown-card {
    border-radius: 8rpx;
    overflow: hidden;
  }
  .main {
    height: calc(100vh - 40rpx);
    padding: 15rpx 15rpx 0 15rpx;
    overflow: auto;
  }

  .add-or-edit-wrapper {
    position: relative;
    background-image: url('http://10.40.0.33:9001/file-storage/540302650699495424-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    padding: 32rpx;
  }

  .fixed-check-box-content {
    display: flex;
    flex-direction: column;
    height: 600rpx;
    background: #fff;
    overflow: hidden;
  }

  /* 顶部操作栏固定 */
  .check-group-button {
    position: sticky;
    top: 0;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 32rpx;
    height: 88rpx;
    background-color: #fff;
    font-size: 24rpx;
  }

  .cancel-btn {
    color: #969799;
  }

  .ok-btn {
    color: #1989f9;
    font-weight: 500;
  }

  /* 滚动内容区域 */
  .check-scroll {
    flex: 1;
    overflow-y: scroll;
  }
  /* 滚动内容区域 */
  .form-body {
    height: calc(100vh - 300rpx);
    overflow-y: auto;
    position: relative;
  }
  .form-body-title {
    font-size: 36rpx;
    color: #ffffff;
    font-weight: 600;
    margin: 50rpx 0 32rpx 0;
  }
  .top-title {
    text-align: center;
    padding: 10px 16px;
    height: 80rpx;
    font-size: 28rpx;
    font-weight: 600;
    border-bottom: 1px solid #d9d9d9;
  }
  /* 固定底部按钮栏 */
  .footer-bar {
    margin-top: 20rpx;
    display: flex;
    gap: 32rpx;
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
    margin-top: 32rpx;
    .van-button {
      flex: 1;
    }
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .right-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/539774097599838208-source.png');
    background-size: cover;
    height: 36rpx;
    width: 31rpx;
  }
  .base-form-data {
    background-image: url('http://10.40.0.33:9001/file-storage/540292184772261888-source.png');
    background-size: cover;
    border-radius: 32rpx;
    padding: 24rpx;
    position: relative;
    background-color: #fff;
  }
  .form-body:deep(.u-input) {
    background-color: #fff;
  }
  .detail-content {
    background-image: url('http://10.40.0.33:9001/file-storage/540302515475134464-source.png');
    background-size: cover;
    border-radius: 32rpx;
    padding: 24rpx;
    position: relative;
    z-index: 2;
  }
  .owner-msg {
    background-image: url('http://10.40.0.33:9001/file-storage/540302559395788800-source.png');
    background-size: cover;
    border-radius: 32rpx;
    padding: 24rpx;
    position: relative;
    z-index: 2;
  }
  .base-date-img {
    position: absolute;
    right: 0;
    top: 0rpx;
    width: 290rpx;
    height: 200rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540293635292608512-source.png');
    background-size: cover;
  }
  .add-bot {
    width: 120rpx;
    height: 190rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540293788321789952-source.png');
    background-size: cover;
    position: absolute;
    right: 100rpx;
    top: 0;
    z-index: 3;
  }
  .meet-item {
    border-radius: 32rpx;
    padding: 28rpx 24rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540296109514635264-source.png');
    background-size: cover;
    margin-bottom: 32rpx;
  }
  .meet-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16rpx;
  }
  .meet-top-left {
    display: flex;
    gap: 32rpx;
  }
  .area-name {
    border-radius: 16px 2px 16px 2px;
    background: #3366ff;
    padding: 4rpx 16rpx;
    color: #fff;
  }
  .productline-name {
    font-size: 28rpx;
    color: #3366ff;
    font-weight: 400;
  }
  .mgb16 {
    margin-bottom: 16rpx;
  }
  .mgb8 {
    margin-bottom: 8rpx;
  }
  .meet-top-right {
    border-radius: 8rpx;
    background: rgba(51, 102, 255, 0.3);
    font-size: 24rpx;
    color: #ffffff;
    text-align: center;
    line-height: 32rpx;
    font-weight: 400;
    padding: 4rpx 16rpx;
  }
  .factory-name {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 400;
  }
  .content-label {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
  }
  .content-value {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.65);
    font-weight: 400;
  }
  .meet-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .bottom-label {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
  }
  .bottom-value {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 400;
  }
  .opeartion-btn {
    display: flex;
    justify-content: end;
    gap: 16rpx;
  }
  .form-title {
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.85);
    line-height: 44rpx;
    font-weight: 600;
  }
</style>
